import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ListView, RefreshControl, TouchableOpacity, ActivityIndicator, DeviceEventEmitter
} from 'react-native';
import NavigationBar from '../common/NavigationBar'
import DataRepository,{FLAG_STORAGE} from '../expand/dao/DataRepository'
import ScrollableTabView,{DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view'
import {DURATION} from "react-native-easy-toast";
import RepositoryCell from "../common/RepositoryCell";
import RepositoryDetail from "./RepositoryDetail";
import LanguageDao, {FLAG_LANGUAGE} from '../expand/dao/LanguageDao'
import FavoriteDao from '../expand/dao/FavoriteDao'
import Utils from '../util/Utils'
import ProjectModel from '../model/ProjectModel'

const URL = 'https://api.github.com/search/repositories?q='
const QUERY_STR = '&sort=stars'
let favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular)

export default class PopularPage extends Component {
    constructor(props) {
        super(props)
        this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_key)
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular)
        this.dataRepository = new DataRepository()
        this.state={
            result: null,
            dataArray: []
        }
    }
    componentDidMount() {
        this.loadData()
    }
    loadData() {
        this.languageDao.fetch()
            .then((result) => {
                this.setState({
                    dataArray: result
                })
            }).catch((error) => {
            console.log(error)
        })
    }
    render() {
        let content = this.state.dataArray.length > 0 ?
            <ScrollableTabView
                tabBarBackgroundColor='#2196F3'
                tabBarInactiveTextColor='mintcream'
                tabBarActiveTextColor='white'
                tabBarUnderlineStyle={{backgroundColor: '#e7e7e7', height: 2}}
                renderTabBar={() => <ScrollableTabBar />}
            >
                {this.state.dataArray.map((item, i, arr) => {
                    let lan = arr[i];
                    return lan.checked ?  <PopularTab key={i} tabLabel={lan.name} {...this.props}/>:null
                })}
            </ScrollableTabView> : null
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={'最热'}
                    statusBar={{backgroundColor: '#2196f3'}}
                />
                {content}
            </View>
        )
    }
}

class PopularTab extends Component {
    constructor(props) {
        super(props)
        this.dataRepository = new DataRepository(FLAG_STORAGE.flag_popular)
        this.state={
            dataSource: null,
            isLoading: false,
            favoriteKeys: []
        }
    }
    componentWillMount() {
        this.onLoad()
    }
    onSelect(item) {
        this.props.navigator.push({
            component: RepositoryDetail,
            params: {
                item: item,
                ...this.props
            }
        })
    }
    onFavorite(item, isFavorite) {
        if(isFavorite){
            favoriteDao.saveFavoriteItem(item.id.toString(), JSON.stringify(item))
        } else {
            favoriteDao.removeFavoriteItem(item.id.toString())
        }
    }
    renderRow(projectModel) {
        return <RepositoryCell
            onSelect={()=>this.onSelect(projectModel)}
            key={projectModel.item.id}
            projectModel={projectModel}
            onFavorite={(item, isFavorite) => this.onFavorite(item, isFavorite)}/>
    }
    flushFavoriteState() {
        let projectModels = []
        let items = this.items
        for (let i=0; i< items.length; i++) {

            projectModels.push(new ProjectModel(items[i], Utils.checkFavorite(items[i], this.state.favoriteKeys)))
        }
        this.updateState({
            isLoading: false,
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(projectModels)
        })
    }
    getFavoriteKeys() {
        favoriteDao.getFavoriteKeys()
            .then(keys => {
                alert(this.state.favoriteKeys)
                if(key) {
                    this.updateState({
                        favoriteKeys: keys
                    })
                    this.flushFavoriteState()
                }
            })
            .catch(e=>{
                this.flushFavoriteState()
            })
    }
    updateState(dic) {
        if(!dic) return
        this.setState(dic)
    }
    onLoad() {
        this.setState({
            isLoading: true
        })
        let url = URL+this.props.tabLabel+QUERY_STR
        this.dataRepository.fetchRepository(url)
            .then(res => {
                this.items = res && res.items ? res.items: res? res: []

                this.getFavoriteKeys()
                if(res&&res.update_date&&!this.dataRepository.checkDate(res.update_date)) {
                    DeviceEventEmitter.emit('showToast', '数据过时')
                    return this.dataRepository.fetchNetRepository(url)
                } else {
                    DeviceEventEmitter.emit('showToast', '显示缓存数据')
                }
            })
            .then(items => {
                if(!items || items.length === 0) return;
                this.items = items
                this.getFavoriteKeys()
                DeviceEventEmitter.emit('showToast', '显示网络数据')
            })
            .catch(error => {
                this.setState({
                    isLoading: false,
                    result: JSON.stringify(error)
                })
            })
    }
    render() {
        if (!this.state.dataSource) { // myList为空的时候显示加载组件，有数据则展示数据
            return (
            <View>
            <ActivityIndicator
            animating={this.state.animating}
            style={[styles.centering, {height: 80}]}
            size="large"
            />
            </View>
            );
        } else {
            return (
            <View style={styles.container}>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(rowData) => this.renderRow(rowData)}
                    refreshControl={<RefreshControl
                        color={['#2196f3']}
                        tintColor={'#2193f3'}
                        title={'加载中...'}
                        titleColor={'#2193f3'}
                        refreshing={this.state.isLoading}
                        onRefresh={()=>this.onLoad()}
                    />
                    }
                />
            </View>
            )
        }
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    text: {
        fontSize: 20
    },
    row: {
        height: 50
    },
    line: {
        height: 1,
        backgroundColor: 'black'
    },
    centering: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 8,
    },
});